import { globalErrorHandler } from './errorHandler';

// 调试工具，帮助监控错误处理器状态
export const debugErrorHandler = {
  // 检查错误处理器健康状态
  checkHealth() {
    console.group('🔍 Error Handler Health Check');

    try {
      const queue = globalErrorHandler.getErrorQueue();
      console.log('✅ Error queue accessible:', Array.isArray(queue), 'Length:', queue.length);

      // 测试清空功能
      const originalLength = queue.length;
      if (originalLength > 0) {
        console.log('📊 Error queue has', originalLength, 'errors');
        queue.forEach((error, index) => {
          console.log(`Error ${index + 1}:`, error.type, '-', error.message.slice(0, 50) + '...');
        });
      } else {
        console.log('✅ Error queue is empty');
      }
    } catch (error) {
      console.error('❌ Error accessing error handler:', error);
    }

    console.groupEnd();
  },

  // 手动触发测试错误
  triggerTestError(type: 'simple' | 'complex' = 'simple') {
    console.log('🧪 Triggering test error...');

    if (type === 'simple') {
      globalErrorHandler.captureError('Debug test error', 'Debug Test');
    } else {
      try {
        // @ts-ignore
        const obj = null;
        obj.nonExistentProperty.deepProperty = 'test';
      } catch (error) {
        globalErrorHandler.captureError(error, 'Debug Complex Test');
      }
    }

    setTimeout(() => {
      this.checkHealth();
    }, 100);
  },

  // 监控错误处理器状态变化
  startMonitoring() {
    let lastQueueLength = 0;

    const monitor = () => {
      try {
        const queue = globalErrorHandler.getErrorQueue();
        const currentLength = queue.length;

        if (currentLength !== lastQueueLength) {
          console.log(`📊 Error queue changed: ${lastQueueLength} → ${currentLength}`);
          lastQueueLength = currentLength;
        }
      } catch (error) {
        console.error('❌ Error monitoring failed:', error);
      }
    };

    const interval = setInterval(monitor, 1000);

    console.log('👁️ Started error handler monitoring');

    // 返回清理函数
    return () => {
      clearInterval(interval);
      console.log('🛑 Stopped error handler monitoring');
    };
  },

  // 重置错误处理器
  reset() {
    console.log('🔄 Resetting error handler...');

    try {
      globalErrorHandler.clearErrorQueue();
      console.log('✅ Error handler reset successfully');
      this.checkHealth();
    } catch (error) {
      console.error('❌ Failed to reset error handler:', error);
    }
  },
};

// 在开发环境下暴露到全局
if (import.meta.env.DEV) {
  (window as any).debugErrorHandler = debugErrorHandler;
  console.log('🔧 Debug tools available: window.debugErrorHandler');
}
